<template>
  <div class="note-message">
    <BackPreviou class="back-btn" @showMain="handelClick" />
    <div class="content">
      <Form
        :model="formState"
        style="width: 1010px"
        :label-col="{ style: { width: '210px' } }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        label-align="right"
        :colon="false"
      >
        <FormItem
          name="JE_SYS_NOTEDIY"
          class="JE_SYS_NOTEDIY"
          :label="$t('message.secondary.facilitator')"
        >
          <radio-group
            v-model:value="formState.JE_SYS_NOTEDIY"
            :options="facilitatorList"
            class="my-checkbox"
            @change="changeRadio"
          />
          <div class="text">
            <i>{{ $t('message.secondary.facilitatorTip') }}</i>
          </div>
        </FormItem>
        <FormItem name="btn" style="display: none">
          <button class="btnClick" @click="submit">123</button>
        </FormItem>
        <div v-if="formState.JE_SYS_NOTEDIY === 'SYS'" class="sys">
          <FormItem
            name="NOTE_SYS_UID"
            class="NOTE_SYS_UID"
            label="Uid"
            v-bind="validateInfos.NOTE_SYS_UID"
          >
            <Input v-model:value="formState.NOTE_SYS_UID" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.sysUidTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_SYS_KEY"
            class="NOTE_SYS_KEY"
            label="Key"
            v-bind="validateInfos.NOTE_SYS_KEY"
          >
            <Input v-model:value="formState.NOTE_SYS_KEY" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.syskeyTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_SYS_KEY"
            class="NOTE_SYS_KEY"
            label="KeyMD5"
            v-bind="validateInfos.NOTE_SYS_KEY"
          >
            <Input v-model:value="formState.NOTE_SYS_MD5" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.sysKeyMD5Tip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_SYS_SIGNNAME"
            class="NOTE_SYS_SIGNNAME"
            label="SignName"
            v-bind="validateInfos.NOTE_SYS_SIGNNAME"
          >
            <Input v-model:value="formState.NOTE_SYS_SIGNNAME" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.sysSignNameTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_SYS_URL"
            class="NOTE_SYS_URL"
            :label="$t('message.secondary.website')"
          >
            <Input v-model:value="formState.NOTE_SYS_URL" class="myInput" disabled="disabled">
            </Input>
            <div class="deeplink" @click="deepClick(formState.NOTE_SYS_URL)"> </div>
            <div class="text">
              <i>{{ $t('message.secondary.WebsiteTip') }}</i>
            </div>
          </FormItem>
        </div>
        <div v-else-if="formState.JE_SYS_NOTEDIY === '253'" class="chuanglan">
          <FormItem
            name="NOTE_253_USERNAME"
            class="NOTE_253_USERNAME"
            label="Account "
            v-bind="validateInfos.NOTE_253_USERNAME"
          >
            <Input v-model:value="formState.NOTE_253_USERNAME" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.CLAccountTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_253_PASSWORD"
            class="NOTE_253_PASSWORD"
            label="Password  "
            v-bind="validateInfos.NOTE_253_PASSWORD"
          >
            <Input v-model:value="formState.NOTE_253_PASSWORD" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.CLPasswordTip') }}</i>
            </div>
          </FormItem>
          <FormItem name="NOTE_253_REPORT" class="NOTE_253_REPORT" label="Report">
            <Input v-model:value="formState.NOTE_253_REPORT" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.CLReportTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_253_SIGNNAME"
            class="NOTE_253_SIGNNAME"
            label="SignName"
            v-bind="validateInfos.NOTE_253_SIGNNAME"
          >
            <Input v-model:value="formState.NOTE_253_SIGNNAME" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.CLSignNameTip') }} </i>
            </div>
          </FormItem>
          <FormItem name="NOTE_253_TEMPLATE" class="NOTE_253_TEMPLATE" label="Template">
            <Input v-model:value="formState.NOTE_253_TEMPLATE" class="myInput"> </Input>
            <div class="text">
              <i>提示：253管理后台设置的模板编码信息</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_253_SENDURL"
            class="NOTE_253_SENDURL"
            :label="$t('message.secondary.website')"
          >
            <Input v-model:value="formState.NOTE_253_SENDURL" class="myInput" disabled="disabled">
            </Input>
            <div class="deeplink" @click="deepClick(formState.NOTE_253_SENDURL)"></div>
            <div class="text">
              <i>{{ $t('message.secondary.WebsiteTip') }}</i>
            </div>
          </FormItem>
        </div>
        <div v-else-if="formState.JE_SYS_NOTEDIY === 'ALIYUN'" class="aliyun">
          <FormItem name="NOTE_ALIYUN_SIGNNAME" class="NOTE_ALIYUN_SIGNNAME" label="SignName">
            <Input v-model:value="formState.NOTE_ALIYUN_SIGNNAME" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.alyunSignNameTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_ALIYUN_TEMPLATE"
            class="NOTE_ALIYUN_TEMPLATE"
            label="TemplateCode"
            v-bind="validateInfos.NOTE_ALIYUN_TEMPLATE"
          >
            <Input v-model:value="formState.NOTE_ALIYUN_TEMPLATE" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.alyunTemplateCodeTip') }}</i>
            </div>
          </FormItem>
          <FormItem name="NOTE_ALIYUN_ACCESSKEY" class="NOTE_ALIYUN_ACCESSKEY" label="AccessKey ID">
            <Input v-model:value="formState.NOTE_ALIYUN_ACCESSKEY" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.alyunAccessKeyIDTip') }}</i>
            </div>
          </FormItem>
          <FormItem name="NOTE_ALIYUN_SECRET" class="NOTE_ALIYUN_SECRET" label="AccessKey Secret">
            <Input v-model:value="formState.NOTE_ALIYUN_SECRET" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.alyunAccessKeySecretTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_ALIYUN_URL"
            class="NOTE_ALIYUN_URL"
            :label="$t('message.secondary.website')"
          >
            <Input v-model:value="formState.NOTE_ALIYUN_URL" class="myInput" disabled="disabled">
            </Input>
            <div class="deeplink" @click="deepClick(formState.NOTE_ALIYUN_URL)"></div>
            <div class="text">
              <i>{{ $t('message.secondary.WebsiteTip') }}</i>
            </div>
          </FormItem>
        </div>
        <div v-else-if="formState.JE_SYS_NOTEDIY === 'DIY'" class="diy">
          <FormItem
            name="NOTE_DIY_CLASS"
            class="NOTE_DIY_CLASS"
            :label="$t('message.secondary.method')"
          >
            <Input v-model:value="formState.NOTE_DIY_CLASS" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.methodTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="NOTE_DIY_URL"
            class="NOTE_DIY_URL"
            :label="$t('message.secondary.website')"
          >
            <Input v-model:value="formState.NOTE_DIY_URL" class="myInput"> </Input>
            <div class="text">
              <i>{{ $t('message.secondary.WebsiteTip') }}</i>
            </div>
          </FormItem>
        </div>
      </Form>
    </div>
  </div>
</template>

<script>
  import { Input, Form, Radio, Modal } from '@jecloud/ui';
  import VueEvent from '@/helper/model/event';
  import BackPreviou from '@/components/back-previou.vue';
  import { reactive, ref, onUnmounted } from 'vue';
  import { useOpenDialog } from '@/hooks/index';
  import { saveConfigData } from '@/api';
  import { onScroll } from '@/utils/utils';
  import { useI18n } from '@common/locales';

  const useForm = Form.useForm;
  export default {
    name: 'NoteMessage',
    components: {
      Form,
      FormItem: Form.Item,
      Input,
      RadioGroup: Radio.Group,
      BackPreviou,
    },
    props: {
      dataAll: {
        type: Array,
        default: () => [],
      },
      subpageName: {
        type: String,
        default: '',
      },
    },
    emits: ['showMain'],
    setup(props, { emit }) {
      // 搜索到子页面
      if (props.subpageName) {
        formState.JE_SYS_NOTEDIY = ref(props.subpageName.value);
      }
      // code,用于请求携带的参数
      const typeConfig = {
        SYS: 'SYS',
        253: '253',
        ALIYUN: 'ALIYUN',
        DIY: 'DIY',
      };
      // 关闭子页面
      const closePage = () => {
        emit('showMain', false);
      };

      // 点击返回
      const handelClick = () => {
        VueEvent.emit('saveResult', isChange());
        if (isChange()) return closePage();
        useOpenDialog({
          attribute: 'message-push',
          allFields: JSON.stringify(formState),
          type: typeConfig[formState.JE_SYS_NOTEDIY],
          // type: '',
        });
      };

      // 表单数据
      let formState = reactive({
        JE_SYS_NOTEDIY: 'SYS',
        NOTE_SYS_UID: '',
        NOTE_SYS_KEY: '',
        NOTE_SYS_MD5: '',
        NOTE_SYS_SIGNNAME: '',
        NOTE_SYS_URL: 'http://www.smschinese.cn/api.shtml',
        NOTE_253_USERNAME: '',
        NOTE_253_PASSWORD: '',
        NOTE_253_REPORT: '',
        NOTE_253_SIGNNAME: '',
        NOTE_253_TEMPLATE: '',
        NOTE_253_SENDURL: 'https://www.chuanglan.com/',
        NOTE_ALIYUN_SIGNNAME: '',
        NOTE_ALIYUN_TEMPLATE: '',
        NOTE_ALIYUN_ACCESSKEY: '',
        NOTE_ALIYUN_SECRET: '',
        NOTE_ALIYUN_URL: 'https://www.aliyun.com/product/sms',
        NOTE_DIY_CLASS: '',
        NOTE_DIY_URL: '',
      });

      // 对比项
      let meta = {};
      let res = {};
      // 转换数据用于回显
      const changeDataType = () => {
        res = props.dataAll.filter((item) => {
          return item.key === 'NoteMessage';
        });
        res[0]?.items.find((item) => {
          formState[item.code] = item.value;
        });
        meta = JSON.parse(JSON.stringify(formState));
      };
      changeDataType('props', props.dataAll);

      // 表单数据是否改变
      const isChange = () => {
        let res = Object.keys(meta);
        return res.every((item) => {
          return meta[item] === formState[item];
        });
      };
      // 互斥校验规则
      let isValid = false; // 是否单独校验
      const validatePass = () => {
        if (formState.NOTE_SYS_UID && formState.NOTE_SYS_SIGNNAME) {
          isValid = true;
          if (formState.NOTE_SYS_KEY === '' && formState.NOTE_SYS_MD5 === '') {
            return Promise.reject('key与keyMD5字段为二选一必填项字段，请选其中之一');
          } else if (formState.NOTE_SYS_KEY !== '' && formState.NOTE_SYS_MD5 !== '') {
            return Promise.reject('key与keyMD5为互斥字段，有且只有一个');
          } else {
            return Promise.resolve();
          }
        } else {
          return Promise.resolve();
        }
      };

      // 使用useForm进行表单校验
      let rulesRef = reactive({
        NOTE_SYS_UID: [{ required: true, message: '该输入项为必填项' }],
        NOTE_SYS_SIGNNAME: [{ required: true, message: '该输入项为必填项' }],
        NOTE_SYS_KEY: [{ validator: validatePass }],
        NOTE_SYS_MD5: [{ validator: validatePass }],
        NOTE_253_USERNAME: [{ required: true, message: '该输入项为必填项' }],
        NOTE_253_PASSWORD: [{ required: true, message: '该输入项为必填项' }],
        NOTE_253_SIGNNAME: [{ required: true, message: '该输入项为必填项' }],
        NOTE_ALIYUN_TEMPLATE: [{ required: true, message: '该输入项为必填项' }],
      });

      const temp = JSON.parse(JSON.stringify({ ...rulesRef }));
      // 根据type确定校验对象
      //#region
      const changRule = () => {
        if (formState.JE_SYS_NOTEDIY === 'SYS') {
          rulesRef.NOTE_SYS_UID = temp.NOTE_SYS_UID;
          rulesRef.NOTE_SYS_SIGNNAME = temp.NOTE_SYS_SIGNNAME;
          rulesRef.NOTE_SYS_KEY = [{ validator: validatePass }];
          rulesRef.NOTE_SYS_MD5 = [{ validator: validatePass }];
          rulesRef.NOTE_253_USERNAME = [{ required: false }];
          rulesRef.NOTE_253_PASSWORD = [{ required: false }];
          rulesRef.NOTE_253_SIGNNAME = [{ required: false }];
          rulesRef.NOTE_ALIYUN_TEMPLATE = [{ required: false }];
        } else if (formState.JE_SYS_NOTEDIY === '253') {
          rulesRef.NOTE_SYS_UID = [{ required: false }];
          rulesRef.NOTE_SYS_SIGNNAME = [{ required: false }];
          rulesRef.NOTE_SYS_KEY = [{ required: false }];
          rulesRef.NOTE_SYS_MD5 = [{ required: false }];
          rulesRef.NOTE_253_USERNAME = temp.NOTE_253_USERNAME;
          rulesRef.NOTE_253_PASSWORD = temp.NOTE_253_PASSWORD;
          rulesRef.NOTE_253_SIGNNAME = temp.NOTE_253_SIGNNAME;
          rulesRef.NOTE_ALIYUN_TEMPLATE = [{ required: false }];
        } else if (formState.JE_SYS_NOTEDIY === 'ALIYUN') {
          rulesRef.NOTE_SYS_UID = [{ required: false }];
          rulesRef.NOTE_SYS_SIGNNAME = [{ required: false }];
          rulesRef.NOTE_SYS_KEY = [{ required: false }];
          rulesRef.NOTE_SYS_MD5 = [{ required: false }];
          rulesRef.NOTE_253_USERNAME = [{ required: false }];
          rulesRef.NOTE_253_PASSWORD = [{ required: false }];
          rulesRef.NOTE_253_SIGNNAME = [{ required: false }];
          rulesRef.NOTE_ALIYUN_TEMPLATE = temp.NOTE_ALIYUN_TEMPLATE;
        } else {
          rulesRef.NOTE_SYS_UID = [{ required: false }];
          rulesRef.NOTE_SYS_SIGNNAME = [{ required: false }];
          rulesRef.NOTE_SYS_KEY = [{ required: false }];
          rulesRef.NOTE_SYS_MD5 = [{ required: false }];
          rulesRef.NOTE_253_USERNAME = [{ required: false }];
          rulesRef.NOTE_253_PASSWORD = [{ required: false }];
          rulesRef.NOTE_253_SIGNNAME = [{ required: false }];
          rulesRef.NOTE_ALIYUN_TEMPLATE = [{ required: false }];
        }
      };
      changRule();
      //#endregion
      const changeRadio = () => {
        changRule();
      };
      const formRef = ref();
      const { resetFields, validate, validateInfos } = useForm(formState, rulesRef, {
        onValidate: () => {
          // 校验互斥另一项
          if (isValid) {
            validate(['NOTE_SYS_KEY']);
            validate(['NOTE_SYS_MD5']);
          }
          isValid = false;
        },
      });
      // 修改数据
      const SaveConfigDataEvent = () => {
        saveConfigData({
          attribute: 'message-push',
          allFields: JSON.stringify(formState),
          // type: typeConfig[formState.JE_SYS_NOTEDIY],
          type: '',
        }).then(
          (meta = JSON.parse(JSON.stringify(formState))),
          Modal.notice('保存成功', 'success'),
          VueEvent.emit('changeAllData', {
            item: 'message-push',
            formState,
          }),
        );
      };

      // 提交表单
      const submit = () => {
        validate()
          .then(() => {
            // 验证成功
            if (isChange()) return Modal.notice('无数据操作!', 'info');
            // 发请求
            SaveConfigDataEvent();
          })
          .catch((err) => {
            if (err.errorFields.length === 0) {
              // 小bug，表单其实已经验证通过了，但还是被catch到了，这里做处理
              if (isChange()) return Modal.notice('无数据操作!', 'info');
              SaveConfigDataEvent();
            }
            // 验证失败弹框
            const res = err.errorFields.filter((item) => {
              return (
                item.errors[0] === 'key与keyMD5字段为二选一必填项字段，请选其中之一' ||
                item.errors[0] === 'key与keyMD5为互斥字段，有且只有一个'
              );
            });
            if (res.length > 0) {
              if (formState.NOTE_SYS_UID && formState.NOTE_SYS_SIGNNAME) {
                Modal.alert(res[0].errors[0], 'error');
              }
            }
          });
      };
      const I18n = useI18n().messages.zh_CN;
      // 单选数据
      const facilitatorList = reactive([
        { label: I18n.message.secondary.sys, value: 'SYS' },
        { label: I18n.message.secondary.chuanlan, value: '253' },
        { label: I18n.message.secondary.alyun, value: 'ALIYUN' },
        { label: I18n.message.secondary.diy, value: 'DIY' },
      ]);
      // 校验成功

      // 保存回调
      const clickCallback = () => {
        submit();
      };
      // 滚动事件
      const onScrollDe = (data) => {
        formState.JE_SYS_NOTEDIY = data.name;
        setTimeout(() => {
          onScroll();
        }, 0);
      };

      // deeplink跳转
      const deepClick = (payload) => {
        if (payload) {
          // console.log(payload);
          window.open(payload);
        }
      };
      VueEvent.on('closeEvent', closePage);
      VueEvent.on('toolbarSaveEvent', clickCallback);
      VueEvent.on('fadeScrollSed', onScrollDe);
      VueEvent.on('validateNote', clickCallback);
      VueEvent.on('isSave', handelClick);
      onUnmounted(() => {
        VueEvent.off('closeEvent', closePage);
        VueEvent.off('fadeScrollSed', onScrollDe);
        VueEvent.off('toolbarSaveEvent', clickCallback);
        VueEvent.off('validateNote', clickCallback);
        VueEvent.off('isSave', handelClick);
      });

      return {
        handelClick,
        formState,
        facilitatorList,
        validateInfos,
        resetFields,
        submit,
        formRef,
        changeRadio,
        rulesRef,
        validate,
        deepClick,
      };
    },
  };
</script>

<style lang="less" scoped>
  .note-message {
    margin-left: -100px;
    .content {
      padding-top: 20px;
    }
    .deeplink {
      top: 2px;
      left: 0;
      position: absolute;
      height: 28px;
      width: 240px;
      z-index: 999;
      opacity: 0.1;
      &:hover {
        cursor: pointer;
      }
    }
    .tips {
      margin-left: 100px;
      margin-top: 30px;
      padding: 12px 20px 0px 20px;
      width: 810px;
      height: 74px;
      border: 1px solid #abd09d;
      background: #eff9f2;
      color: #36761f;
      border-radius: 2px;
      font-size: 14px;
      color: #333333;
      line-height: 15px;
    }
  }
</style>
